const express = require('express');
const router = express.Router();
const { pool } = require('../config/database');

// 获取用户地址列表
router.get('/user/:userId', async (req, res) => {
  try {
    const userId = req.params.userId;
    
    const [addresses] = await pool.execute(
      'SELECT id, name, phone, tag_name, province_code, city_code, district_code, address, full_address, is_default, create_time, update_time FROM user_address WHERE user_id = ? AND is_deleted = 0 ORDER BY is_default DESC, create_time DESC',
      [userId]
    );

    res.json({
      success: true,
      message: '获取地址列表成功',
      data: addresses
    });
  } catch (error) {
    console.error('获取地址列表失败:', error);
    res.status(500).json({
      success: false,
      message: '获取地址列表失败',
      error: error.message
    });
  }
});

// 获取单个地址详情
router.get('/:id', async (req, res) => {
  try {
    const addressId = req.params.id;
    
    const [addresses] = await pool.execute(
      'SELECT id, user_id, name, phone, tag_name, province_code, city_code, district_code, address, full_address, is_default FROM user_address WHERE id = ? AND is_deleted = 0',
      [addressId]
    );

    if (addresses.length === 0) {
      return res.status(404).json({
        success: false,
        message: '地址不存在'
      });
    }

    res.json({
      success: true,
      message: '获取地址详情成功',
      data: addresses[0]
    });
  } catch (error) {
    console.error('获取地址详情失败:', error);
    res.status(500).json({
      success: false,
      message: '获取地址详情失败',
      error: error.message
    });
  }
});

// 添加用户地址
router.post('/', async (req, res) => {
  try {
    const { user_id, name, phone, tag_name, province_code, city_code, district_code, address, full_address, is_default } = req.body;
    
    // 验证必填字段
    if (!user_id || !name || !phone || !address) {
      return res.status(400).json({
        success: false,
        message: '用户ID、姓名、电话和详细地址不能为空'
      });
    }

    // 如果设置为默认地址，先将该用户的其他地址设为非默认
    if (is_default === 1) {
      await pool.execute(
        'UPDATE user_address SET is_default = 0 WHERE user_id = ? AND is_deleted = 0',
        [user_id]
      );
    }

    // 创建地址
    const [result] = await pool.execute(
      'INSERT INTO user_address (user_id, name, phone, tag_name, province_code, city_code, district_code, address, full_address, is_default) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)',
      [user_id, name, phone, tag_name || '', province_code || '', city_code || '', district_code || '', address, full_address || '', is_default || 0]
    );

    res.status(201).json({
      success: true,
      message: '添加地址成功',
      data: {
        id: result.insertId,
        user_id,
        name,
        phone,
        tag_name,
        province_code,
        city_code,
        district_code,
        address,
        full_address,
        is_default: is_default || 0
      }
    });
  } catch (error) {
    console.error('添加地址失败:', error);
    res.status(500).json({
      success: false,
      message: '添加地址失败',
      error: error.message
    });
  }
});

// 更新用户地址
router.put('/:id', async (req, res) => {
  try {
    const addressId = req.params.id;
    const { name, phone, tag_name, province_code, city_code, district_code, address, full_address, is_default } = req.body;

    // 检查地址是否存在
    const [addresses] = await pool.execute(
      'SELECT user_id FROM user_address WHERE id = ? AND is_deleted = 0',
      [addressId]
    );

    if (addresses.length === 0) {
      return res.status(404).json({
        success: false,
        message: '地址不存在'
      });
    }

    const userId = addresses[0].user_id;

    // 如果设置为默认地址，先将该用户的其他地址设为非默认
    if (is_default === 1) {
      await pool.execute(
        'UPDATE user_address SET is_default = 0 WHERE user_id = ? AND id != ? AND is_deleted = 0',
        [userId, addressId]
      );
    }

    // 更新地址
    await pool.execute(
      'UPDATE user_address SET name = ?, phone = ?, tag_name = ?, province_code = ?, city_code = ?, district_code = ?, address = ?, full_address = ?, is_default = ? WHERE id = ?',
      [name, phone, tag_name || '', province_code || '', city_code || '', district_code || '', address, full_address || '', is_default || 0, addressId]
    );

    res.json({
      success: true,
      message: '更新地址成功'
    });
  } catch (error) {
    console.error('更新地址失败:', error);
    res.status(500).json({
      success: false,
      message: '更新地址失败',
      error: error.message
    });
  }
});

// 设置默认地址
router.put('/:id/default', async (req, res) => {
  try {
    const addressId = req.params.id;

    // 检查地址是否存在并获取用户ID
    const [addresses] = await pool.execute(
      'SELECT user_id FROM user_address WHERE id = ? AND is_deleted = 0',
      [addressId]
    );

    if (addresses.length === 0) {
      return res.status(404).json({
        success: false,
        message: '地址不存在'
      });
    }

    const userId = addresses[0].user_id;

    // 先将该用户的所有地址设为非默认
    await pool.execute(
      'UPDATE user_address SET is_default = 0 WHERE user_id = ? AND is_deleted = 0',
      [userId]
    );

    // 将指定地址设为默认
    await pool.execute(
      'UPDATE user_address SET is_default = 1 WHERE id = ?',
      [addressId]
    );

    res.json({
      success: true,
      message: '设置默认地址成功'
    });
  } catch (error) {
    console.error('设置默认地址失败:', error);
    res.status(500).json({
      success: false,
      message: '设置默认地址失败',
      error: error.message
    });
  }
});

// 删除用户地址
router.delete('/:id', async (req, res) => {
  try {
    const addressId = req.params.id;

    // 检查地址是否存在
    const [addresses] = await pool.execute(
      'SELECT id FROM user_address WHERE id = ? AND is_deleted = 0',
      [addressId]
    );

    if (addresses.length === 0) {
      return res.status(404).json({
        success: false,
        message: '地址不存在'
      });
    }

    // 软删除地址
    await pool.execute(
      'UPDATE user_address SET is_deleted = 1 WHERE id = ?',
      [addressId]
    );

    res.json({
      success: true,
      message: '删除地址成功'
    });
  } catch (error) {
    console.error('删除地址失败:', error);
    res.status(500).json({
      success: false,
      message: '删除地址失败',
      error: error.message
    });
  }
});

module.exports = router;